<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="nav-content">
        <view class="nav-back" @click="goBack">
          <uni-icons type="left" size="20" color="#333"></uni-icons>
        </view>
        <view class="nav-title">商品详情</view>
        <view class="nav-placeholder"></view>
      </view>
    </view>

    <!-- 返回按钮 -->
    <view
      class="back-button"
      :style="{ top: statusBarHeight + 10 + 'px' }"
      @click="goBack"
    >
      <uni-icons type="left" size="24" color="#000000"></uni-icons>
    </view>

    <!-- 商品图片轮播 -->
    <view class="swiper-container">
      <swiper
        class="product-swiper"
        :indicator-dots="true"
        :autoplay="true"
        :interval="5000"
        indicator-color="#e0e0e0"
        indicator-active-color="#ff8d1a"
        circular
      >
        <swiper-item v-for="(img, index) in product.images" :key="index">
          <image :src="img" mode="aspectFill" class="swiper-image"></image>
        </swiper-item>
      </swiper>
    </view>

    <!-- 商品价格信息 -->
    <view class="product-info">
      <view class="product-title">
        {{ product.title }}
      </view>
      <view class="product-price-section">
        <text class="current-price">¥{{ product.price }}</text>
      </view>
      <text class="original-price">价格：¥{{ product.originalPrice }}</text>
      <view class="product-sales">
        <text class="sales-text"
          >快递：{{
            product.courier_fee === "0.00"
              ? "免运费"
              : "¥" + product.courier_fee
          }}</text
        >
        <text class="sales-text">月销{{ product.sold }}</text>
        <text class="sales-text">{{ product.shipping_address }}</text>
      </view>
    </view>

    <!-- 商品描述 -->
    <view class="product-description">
      <view class="section-title"
        >每人限购10件<uni-icons type="more-filled" size="30"></uni-icons
      ></view>
      <view class="section-title" style="font-size: 14px"
        >满78元，享包邮；不包邮地区：新疆，西藏，台湾...</view
      >
      <!-- 添加的分割线 -->
      <view class="divider"></view>
      <view class="section-title" style="font-size: 13px"
        >正品保证 · 破损暴涨 · 赠运费险 · 极速退款 · 七天退换<uni-icons
          type="more-filled"
          size="30"
        ></uni-icons
      ></view>
    </view>

    <!-- 商品参数 -->
    <view class="product-attributes">
      <view class="section-title"
        >产品参数<uni-icons type="more-filled" size="30"></uni-icons
      ></view>
      <view class="attributes-list">
        <view
          class="attribute-item"
          v-for="(param, index) in parsedParams"
          :key="index"
        >
          <text class="attr-name">{{ param.key }}</text>
        </view>
      </view>
      <view class="divider"></view>
      <view class="section-title"
        >选择颜色分类<uni-icons type="more-filled" size="30"></uni-icons
      ></view>
    </view>

    <!-- 商品评价 -->
    <view class="product-comments">
      <view class="section-title"
        >商品评价（{{ product.remark_count }}）<uni-icons
          type="more-filled"
          size="30"
        ></uni-icons
      ></view>
      <view class="divider"></view>
      <view v-if="product.remark_count > 0">
        <view
          class="comment-item"
          v-for="(comment, index) in product.remark"
          :key="index"
        >
          <view class="comment-header">
            <image
              :src="comment.avatar || 'https://jht.jingang.icu/img/home.jpg'"
              mode="aspectFill"
              class="comment-avatar"
            ></image>
            <view class="comment-info">
              <text class="comment-username">{{
                comment.username || "匿名用户"
              }}</text>
            </view>
          </view>
          <view class="comment-content">
            {{ comment.content || "用户未填写评价内容" }}
          </view>
          <view class="comment-footer">
            <view class="comment-footer-item">
              <text class="comment-text"
                >颜色分类：{{ comment.spec || "默认" }}</text
              >
            </view>
          </view>
        </view>
      </view>
      <view v-else class="no-comments">
        <text class="no-comments-text">暂无评价</text>
      </view>
    </view>

    <!-- 商品详情图片 -->
    <view
      class="product-details"
      v-if="product.norm_arr && product.norm_arr.length > 0"
    >
      <image
        v-for="(item, index) in product.norm_arr"
        :key="index"
        :src="item.img"
        mode="widthFix"
        class="detail-image"
        @error="onImageError(index)"
      />
    </view>

    <!-- 类似商品推荐 -->
    <view class="recommend-section">
      <view class="section-title">类似商品</view>
      <view
        class="recommend-list"
        v-if="product.list && product.list.length > 0"
      >
        <view
          class="recommend-item"
          v-for="(item, index) in product.list"
          :key="index"
          @click="goToProductDetail(item.id)"
        >
          <image
            :src="item.img"
            class="recommend-image"
            mode="aspectFill"
          ></image>
          <view class="recommend-info">
            <view class="recommend-title">{{ item.title }}</view>
            <view class="recommend">
              <view class="recommend-price">¥{{ item.price }}</view>
              <view class="recommend-sales">已售{{ item.sold }}件</view>
            </view>
          </view>
        </view>
      </view>
      <view class="no-data" v-else>
        <text class="no-data-text">暂无推荐商品</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="bar-item" @click="goToHome">
        <uni-icons type="home" size="24" color="#666"></uni-icons>
        <text class="bar-text">首页</text>
      </view>
      <view class="bar-item" @click="addToCart">
        <uni-icons type="cart" size="24" color="#666"></uni-icons>
        <text class="bar-text">购物车</text>
      </view>
      <view class="bar-item" @click="toggleFavorite">
        <uni-icons
          :type="isFavorited ? 'heart-filled' : 'heart'"
          size="24"
          :color="isFavorited ? '#ff4757' : '#666'"
        >
        </uni-icons>
        <text class="bar-text">{{ isFavorited ? "已收藏" : "收藏" }}</text>
      </view>
      <view class="action-button add-cart" @click="addToCart">加入购物车</view>
      <view class="action-button buy-now" @click="showPurchaseModal = true"
        >立即购买</view
      >
    </view>

    <!-- 购买弹窗 -->
    <view
      v-if="showPurchaseModal"
      class="purchase-modal-overlay"
      @click="showPurchaseModal = false"
    >
      <view class="purchase-modal" @click.stop>
        <!-- 商品信息 -->
        <view class="modal-product-info">
          <image
            :src="selectedProductImage"
            mode="aspectFill"
            class="modal-product-img"
          ></image>
          <view class="modal-product-details">
            <text class="modal-product-price">¥{{ selectedProductPrice }}</text>
            <text class="modal-product-stock" v-if="selectedProductStock !== null">
              剩余{{ selectedProductStock }}件
            </text>
            <view class="quantity-controls">
              <view class="quantity-btn" @click="decreaseQuantity">-</view>
              <text class="quantity-value">{{ purchaseQuantity }}</text>
              <view class="quantity-btn" @click="increaseQuantity">+</view>
            </view>
          </view>
        </view>

        <view class="divider"></view>

        <!-- 优惠券 -->
        <view class="modal-coupon">
          <text class="coupon-label">优惠：</text>
          <text class="coupon-text">暂无优惠券</text>
        </view>

        <view class="divider"></view>

        <!-- 规格 -->
        <view class="modal-spec" v-if="product.norm && product.norm.length > 0">
          <template v-for="(normItem, index) in product.norm" :key="index">
            <text class="spec-label">
              {{ normItem.name }}：
            </text>
            <view class="spec-values">
              <text 
                class="spec-text" 
                :class="{ 'spec-selected': isSelected(normItem.name, value) }"
                v-for="(value, valueIndex) in normItem.value" 
                :key="valueIndex"
                @click="selectSpec(normItem.name, value)"
              >
                {{ value }}
              </text>
            </view>
          </template>
        </view>
        <view class="modal-spec" v-else>
          <text class="spec-label">规格：</text>
          <text class="spec-text spec-default" style="width: 10%;">默认</text>
        </view>

        <!-- 确认按钮 -->
        <view class="confirm-button" @click="confirmPurchase">
          确认支付¥{{ (selectedProductPrice * purchaseQuantity).toFixed(2) }}
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import uniIcons from "@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue";
import { public_api } from "@/static/public.js";

export default {
  components: {
    uniIcons,
  },
  data() {
    return {
      statusBarHeight: 0,
      productId: "",
      isFavorited: false,
      showPurchaseModal: false, // 控制购买弹窗显示
      purchaseQuantity: 1, // 购买数量
      selectedSpecs: {}, // 存储选中的规格
      selectedProductImage: "", // 选中规格对应的产品图片
      selectedProductPrice: "", // 选中规格对应的产品价格
      selectedProductStock: null, // 选中规格对应的产品库存
      product: {
        id: 1,
        title: "示例商品名称",
        price: "99.00",
        originalPrice: "199.00",
        courier_fee: "0.00",
        sold: 0,
        shipping_address: "福建厦门",
        images: [
          "https://jht.jingang.icu/img/home.jpg",
          "https://jht.jingang.icu/img/home.jpg",
          "https://jht.jingang.icu/img/home.jpg",
        ],
        content:
          "这是商品的详细描述信息。商品质量优良，性价比高，深受消费者喜爱。这是一段较长的商品描述，用于展示商品的详细信息和特点。",
        params: "",
        attributes: [],
        remark: [], // 商品评价列表
        remark_count: 0, // 评价总数
        norm_arr: [], // 商品规格图片数组
        list: [], // 类似商品推荐列表
        norm: [] // 规格数据
      },
    };
  },
  computed: {
    // 解析产品参数
    parsedParams() {
      if (!this.product.params) return [];
      
      // 如果params是字符串，尝试解析其中的HTML标签
      if (typeof this.product.params === 'string') {
        try {
          // 尝试解析JSON格式的参数
          const paramsArray = JSON.parse(this.product.params);
          // 检查是否为数组格式
          if (Array.isArray(paramsArray)) {
            return paramsArray.map(param => ({
              ...param,
              key: this.stripHtmlTags(param.key || ''),
              value: this.stripHtmlTags(param.value || '')
            }));
          }
          // 如果是对象格式，转换为数组
          else if (typeof paramsArray === 'object') {
            return Object.keys(paramsArray).map(key => ({
              key: this.stripHtmlTags(key),
              value: this.stripHtmlTags(paramsArray[key])
            }));
          }
          return [];
        } catch (e) {
          // 如果不是JSON格式，按换行符分割，并处理HTML标签
          return this.product.params
            .split("\n")
            .filter(line => line.trim() !== "")
            .map(line => {
              const colonIndex = line.indexOf(":");
              if (colonIndex > -1) {
                return {
                  key: this.stripHtmlTags(line.substring(0, colonIndex).trim()),
                  value: this.stripHtmlTags(line.substring(colonIndex + 1).trim())
                };
              }
              return { 
                key: this.stripHtmlTags(line), 
                value: "" 
              };
            });
        }
      }
      
      // 如果params是对象或数组
      if (typeof this.product.params === 'object') {
        if (Array.isArray(this.product.params)) {
          return this.product.params.map(param => ({
            ...param,
            key: this.stripHtmlTags(param.key || ''),
            value: this.stripHtmlTags(param.value || '')
          }));
        } else {
          return Object.keys(this.product.params).map(key => ({
            key: this.stripHtmlTags(key),
            value: this.stripHtmlTags(this.product.params[key])
          }));
        }
      }
      
      return [];
    }
  },
  onLoad(options) {
    // 获取设备状态栏高度
    this.getStatusBarHeight();

    // 获取传递的商品ID
    if (options && options.id) {
      this.productId = options.id;
      // 调用接口获取商品详情
      this.getProductDetail(this.productId);
    } else {
      console.warn("未接收到商品ID参数");
    }
  },
  methods: {
    // 去除HTML标签
    stripHtmlTags(html) {
      if (!html) return '';
      // 使用正则表达式去除HTML标签
      return html.replace(/<[^>]*>/g, '');
    },
    
    // 获取设备状态栏高度
    getStatusBarHeight() {
      try {
        const systemInfo = uni.getSystemInfoSync();
        this.statusBarHeight = systemInfo.statusBarHeight || 0;
      } catch (err) {
        console.error("获取状态栏高度失败", err);
      }
    },

    // 获取商品详情
    getProductDetail(id) {
      // 获取用户ID
      const userId = uni.getStorageSync("userId");
      let uid = "";
      if (userId) {
        uid = userId;
      }

      console.log("请求商品详情参数:", { id: id, uid: uid });

      // 调用商品详情接口
      uni.request({
        url: public_api + "/api/goods/detail",
        method: "POST",
        data: {
          id: id,
          uid: uid,
        },
        success: (res) => {
          console.log("商品详情接口返回完整数据:", res);

          if (res.data && res.data.code === 1) {
            // 打印商品详情数据
            console.log("商品详情数据:", res.data);

            // 处理返回的商品数据
            const goodsData = res.data.data;

            // 处理图片数组
            let images = [];
            if (goodsData.imgs) {
              images = goodsData.imgs.split(",");
            }

            // 处理norm_arr数据
            let normArr = [];
            if (goodsData.norm_arr && Array.isArray(goodsData.norm_arr)) {
              normArr = goodsData.norm_arr;
            }

            // 处理类似商品推荐列表
            let similarProducts = [];
            if (goodsData.list && Array.isArray(goodsData.list)) {
              similarProducts = goodsData.list;
            }

            // 处理规格数据
            let normData = [];
            if (goodsData.norm && Array.isArray(goodsData.norm)) {
              normData = goodsData.norm;
            }

            this.product = {
              id: goodsData.id || id,
              title: goodsData.title || "商品名称",
              price: goodsData.price || "0.00",
              originalPrice: goodsData.original_price || "0.00",
              courier_fee: goodsData.courier_fee || "0.00",
              sold: goodsData.sold || 0,
              shipping_address: goodsData.shipping_address || "",
              images: images,
              content: goodsData.content || "暂无商品描述",
              params: goodsData.params || "",
              attributes: [],
              remark: goodsData.remark || [], // 商品评价列表
              remark_count: goodsData.remark_count || 0, // 评价总数
              norm_arr: normArr, // 商品规格图片数组
              list: similarProducts, // 类似商品推荐列表
              norm: normData // 规格数据
            };

            // 设置收藏状态
            this.isFavorited = goodsData.star === 1;
            
            // 使用 $nextTick 确保 DOM 更新后再初始化规格选择
            this.$nextTick(() => {
              // 初始化规格选择
              this.initSpecSelection();
            });
          } else {
            uni.showToast({
              title:
                res.data && res.data.msg ? res.data.msg : "获取商品详情失败",
              icon: "none",
              duration: 2000,
            });
            console.error("获取商品详情失败:", res);
          }
        },
        fail: (err) => {
          console.error("获取商品详情失败", err);
          uni.showToast({
            title: "网络请求失败，请检查网络连接",
            icon: "none",
            duration: 2000,
          });
        },
        complete: () => {
          console.log("商品详情请求完成");
        },
      });
    },

    // 返回上一页
    goBack() {
      uni.navigateBack({
        delta: 1,
      });
    },

    // 跳转到首页
    goToHome() {
      uni.switchTab({
        url: "/pages/index/index",
      });
    },

 // 显示购买弹窗
    showPurchaseModalFunc() {
      // 设置默认规格
      this.setDefaultSpecs();
      this.showPurchaseModal = true;
      // 确保在弹窗显示后更新信息
      this.$nextTick(() => {
        this.updateSelectedProductInfo();
      });
    },
    // 立即购买 - 显示弹窗
    buyNow() {
      this.showPurchaseModalFunc();
    },
     // 选择规格
    selectSpec(specName, specValue) {
      console.log('selectSpec called:', specName, specValue);
      // 设置选中的规格
      this.$set(this.selectedSpecs, specName, specValue);
      console.log('Updated selectedSpecs:', this.selectedSpecs);
      
      // 查找匹配的规格数据
      this.$nextTick(() => {
        this.updateSelectedProductInfo();
      });
    },
    
    // 根据选中的规格更新产品信息
    updateSelectedProductInfo() {
      console.log('updateSelectedProductInfo called');
      console.log('selectedSpecs:', this.selectedSpecs);
      console.log('norm_arr:', this.product.norm_arr);
      console.log('norm:', this.product.norm);
      
      // 如果没有规格数组，则使用默认信息
      if (!this.product.norm_arr || this.product.norm_arr.length === 0) {
        this.selectedProductImage = this.product.images[0];
        this.selectedProductPrice = this.product.price;
        this.selectedProductStock = null;
        console.log('No norm_arr data, using default image and price');
        return;
      }
      
      // 检查是否已经选择完所有规格
      const selectedSpecKeys = Object.keys(this.selectedSpecs);
      if (this.product.norm && selectedSpecKeys.length !== this.product.norm.length) {
        console.log('Not all specs selected yet');
        // 还没选择完所有规格，不进行匹配
        return;
      }
      
      // 构造用于匹配的对象
      const selectedValues = {};
      Object.keys(this.selectedSpecs).forEach(key => {
        selectedValues[key] = this.selectedSpecs[key];
      });
      
      // 查找匹配的规格数据
      let matchedProduct = null;
      
      // 遍历所有规格数据
      for (let i = 0; i < this.product.norm_arr.length; i++) {
        const item = this.product.norm_arr[i];
        let isMatch = true;
        
        console.log('Checking item:', item);
        
        // 检查每个选中的规格是否都能在这个item中找到匹配
        for (const specName in selectedValues) {
          console.log(`Comparing spec ${specName}: ${item[specName]} with selected ${selectedValues[specName]}`);
          // 直接比较规格名和值
          if (item[specName] !== selectedValues[specName]) {
            isMatch = false;
            console.log('No match for spec:', specName);
            break;
          }
        }
        
        if (isMatch) {
          matchedProduct = item;
          console.log('Found matching product:', matchedProduct);
          break;
        }
      }
      
      // 如果找到匹配项，更新图片、价格和库存
      if (matchedProduct) {
        this.selectedProductImage = matchedProduct.img || this.product.images[0];
        this.selectedProductPrice = matchedProduct.price || this.product.price;
        this.selectedProductStock = matchedProduct.stock !== undefined ? matchedProduct.stock : null;
        console.log('Updated to matched product info:', {
          image: this.selectedProductImage,
          price: this.selectedProductPrice,
          stock: this.selectedProductStock
        });
      } else {
        // 没有找到匹配项，使用默认信息
        this.selectedProductImage = this.product.images[0];
        this.selectedProductPrice = this.product.price;
        this.selectedProductStock = null;
        console.log('No matching product found, using default info');
      }
    },
    
    // 初始化规格选择
    initSpecSelection() {
      // 页面加载完成后初始化规格选择
      this.$nextTick(() => {
        this.setDefaultSpecs();
      });
    },

    // 设置默认规格
    setDefaultSpecs() {
      // 清空之前的选择
      this.selectedSpecs = {};
      
      // 如果有规格数据
      if (this.product.norm && this.product.norm.length > 0) {
        this.product.norm.forEach(normItem => {
          if (normItem.value && normItem.value.length > 0) {
            // 默认选择第一个规格值
            this.$set(this.selectedSpecs, normItem.name, normItem.value[0]);
          }
        });
      }
      
      // 初始化选中产品的信息
      this.selectedProductImage = this.product.images[0];
      this.selectedProductPrice = this.product.price;
      this.selectedProductStock = null;
      
      // 更新选中规格对应的产品信息
      this.updateSelectedProductInfo();
    },
    
    // 判断规格是否被选中
    isSelected(specName, specValue) {
      return this.selectedSpecs[specName] === specValue;
    },

    // 确认购买
    confirmPurchase() {
      // 检查是否选择了所有规格
      let allSpecsSelected = true;
      let selectedSpecText = "";
      
      if (this.product.norm && this.product.norm.length > 0) {
        // 检查是否所有规格都已选择
        for (let i = 0; i < this.product.norm.length; i++) {
          const normItem = this.product.norm[i];
          if (!this.selectedSpecs[normItem.name]) {
            allSpecsSelected = false;
            break;
          }
        }
        
        // 如果所有规格都已选择，构建规格文本
        if (allSpecsSelected) {
          for (let key in this.selectedSpecs) {
            if (this.selectedSpecs[key]) {
              selectedSpecText += `${key}:${this.selectedSpecs[key]} `;
            }
          }
        }
      } else {
        // 没有规格选项，使用默认
        selectedSpecText = "默认";
        allSpecsSelected = true;
      }
      
      // 如果没有选择所有规格，提示用户
      if (!allSpecsSelected) {
        uni.showToast({
          title: "请选择规格",
          icon: "none",
          duration: 2000,
        });
        return;
      }
      
      this.showPurchaseModal = false;
      
      // 将商品信息打包成 JSON 字符串传递
      const productInfo = {
        id: this.product.id,
        title: this.product.title,
        price: this.selectedProductPrice, // 使用选中的价格
        images: this.product.images,
        spec: selectedSpecText.trim() || "默认"
      };
      
      // 跳转到支付页面，传递商品信息和购买数量以及选中规格
      uni.navigateTo({
        url: `/pages/pay/pay?productInfo=${encodeURIComponent(JSON.stringify(productInfo))}&quantity=${this.purchaseQuantity}`
      });
    },

    // 减少购买数量
    decreaseQuantity() {
      if (this.purchaseQuantity > 1) {
        this.purchaseQuantity--;
      }
    },

    // 增加购买数量
    increaseQuantity() {
      // 限制最大购买数量为10件（根据页面中的"每人限购10件"提示）
      if (this.purchaseQuantity < 10) {
        this.purchaseQuantity++;
      } else {
        uni.showToast({
          title: "每人限购10件",
          icon: "none",
          duration: 1500,
        });
      }
    },

    // 添加/取消收藏
    toggleFavorite() {
      // 获取用户ID
      const userId = uni.getStorageSync("userId");
      
      if (!userId) {
        // 如果用户未登录，提示登录
        uni.showToast({
          title: "请先登录",
          icon: "none",
          duration: 2000
        });
        // 跳转到登录页面
        setTimeout(() => {
          uni.navigateTo({
            url: "/pages/login/login"
          });
        }, 2000);
        return;
      }
      
      if (this.isFavorited) {
        // 取消收藏
        uni.request({
          url: public_api + "/api/goods/cancel_star",
          method: "POST",
          data: {
            uid: userId,
            id: this.productId
          },
          success: (res) => {
            if (res.data && res.data.code === 1) {
              this.isFavorited = false;
              uni.showToast({
                title: "已取消收藏",
                icon: "success",
              });
            } else {
              uni.showToast({
                title: res.data.msg || "取消收藏失败",
                icon: "none",
              });
            }
          },
          fail: (err) => {
            console.error("取消收藏失败", err);
            uni.showToast({
              title: "网络请求失败",
              icon: "none",
            });
          }
        });
      } else {
        // 添加收藏
        uni.request({
          url: public_api + "/api/goods/star",
          method: "POST",
          data: {
            uid: userId,
            id: this.productId
          },
          success: (res) => {
            if (res.data && res.data.code === 1) {
              this.isFavorited = true;
              uni.showToast({
                title: "已收藏",
                icon: "success",
              });
            } else {
              uni.showToast({
                title: res.data.msg || "收藏失败",
                icon: "none",
              });
            }
          },
          fail: (err) => {
            console.error("收藏失败", err);
            uni.showToast({
              title: "网络请求失败",
              icon: "none",
            });
          }
        });
      }
    },

    // 跳转到商品详情页
    goToProductDetail(id) {
      uni.navigateTo({
        url: `/pages/product/product?id=${id}`,
      });
    },
  },
  mounted() {
    // 页面挂载后初始化规格选择
    this.initSpecSelection();
  },
};
</script>

<style scoped>
.container {
  width: 100%;
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 100rpx;
  box-sizing: border-box;
  padding-top: 44px; /* 为顶部导航栏留出空间 */
}

/* 顶部导航栏 */
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 44px;
  background-color: #ffffff;
  z-index: 1000;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
}

.nav-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  padding: 0 15px;
  box-sizing: border-box;
}

.nav-back {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-title {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}

.nav-placeholder {
  width: 30px;
}

/* 返回按钮 */
.back-button {
  position: fixed;
  left: 20rpx;
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

/* 轮播图区域 */
.swiper-container {
  width: 100%;
  background-color: #fff;
  margin-top: 40px; /* 添加顶部边距，避免被导航栏遮挡 */
}

.product-swiper {
  height: 500rpx;
}

.swiper-image {
  width: 100%;
  height: 100%;
}

/* 商品信息 */
.product-info {
  width: 100%;
  background-color: #fff;
  padding: 20rpx;
  box-sizing: border-box;
  margin-bottom: 20rpx;
}

.product-title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 20rpx;
  line-height: 1.4;
}

.product-price-section {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.current-price {
  font-size: 36rpx;
  color: #f87d00;
  margin-right: 20rpx;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}

.product-sales {
  display: flex;
  justify-content: space-between;
  font-size: 24rpx;
  color: #999;
  width: 70%;
}

/* 商品描述 */
.product-description {
  width: 100%;
  background-color: #fff;
  padding: 16rpx;
  box-sizing: border-box;
  margin-bottom: 10rpx;
}

/* 商品参数 */
.product-attributes {
  width: 100%;
  background-color: #fff;
  padding: 16rpx;
  box-sizing: border-box;
  margin-bottom: 18rpx;
}

.attributes-list {
  padding: 0 20rpx;
}

.attribute-item {
  display: flex;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.attribute-item:last-child {
  border-bottom: none;
}

.attr-name {
  flex: 1;
  color: #666;
  font-size: 28rpx;
}

.attr-value {
  flex: 2;
  color: #333;
  font-size: 28rpx;
}

/* 通用标题样式 */
.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  padding-bottom: 5rpx;
  border-bottom: 1rpx solid #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.description-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

/* 新增的分割线样式 */
.divider {
  height: 2rpx;
  background-color: #cccccc;
  margin: 20rpx 0;
}

/* 商品评价 */
.product-comments {
  width: 100%;
  background-color: #fff;
  padding: 20rpx;
  box-sizing: border-box;
  margin-bottom: 20rpx;
}

.comment-item {
  display: flex;
  /* align-items: center; */
  flex-direction: column;
  margin-bottom: 20rpx;
}

.comment-header {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.comment-avatar {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 20rpx;
}

.comment-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.comment-content {
  flex: 1;
  font-size: 30rpx;
  line-height: 1.6;
  overflow: hidden;
  text-overflow: ellipsis;
}

.comment-text {
  font-size: 28rpx;
  color: #999999;
}

/* 商品详情图片 */
.product-details {
  width: 100%;
  background-color: #fff;
  padding: 20rpx;
  box-sizing: border-box;
  margin-bottom: 20rpx;
}

.detail-image {
  width: 100%;
  height: auto;
  display: block;
  margin-bottom: 20rpx;
}

.detail-image:last-child {
  margin-bottom: 0;
}

/* 推荐商品 */
.recommend-section {
  width: 100%;
  background-color: #fff;
  padding: 20rpx;
  box-sizing: border-box;
  margin-bottom: 20rpx;
}

.recommend-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.recommend-item {
  width: 48%;
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.recommend {
  display: flex;
}

.recommend-image {
  width: 100%;
  height: 200rpx;
}

.recommend-info {
  padding: 15rpx;
  display: flex;
  flex-direction: column;
}

.recommend-title {
  width: 100%;
  font-size: 34rpx;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  margin-bottom: 10rpx;
  height: 68rpx;
}

.recommend-price {
  font-size: 28rpx;
  color: #f87d00;
  font-weight: bold;
  margin-bottom: 5rpx;
}

.recommend-sales {
  font-size: 20rpx;
  color: #999;
  margin-left: 6px;
}

/* 无数据样式 */
.no-data {
  text-align: center;
  padding: 40rpx 0;
}

.no-data-text {
  font-size: 28rpx;
  color: #999;
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 999;
}

.bar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  height: 100%;
}

.bar-text {
  font-size: 20rpx;
  color: #666;
  margin-top: 5rpx;
}

.action-button {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80%;
  color: #fdf9f9;
  font-weight: bold;
}

.add-cart {
  width: 200rpx;
  background-color: #ff0000;
  border-top-left-radius: 25px;
  border-bottom-left-radius: 25px;
}

.buy-now {
  width: 200rpx;
  background-color: #ff8d1a;
  border-bottom-right-radius: 25px;
  border-top-right-radius: 25px;
}

/* 购买弹窗样式 */
.purchase-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: flex-end;
  z-index: 9999;
}

.purchase-modal {
  width: 100%;
  background-color: #fff;
  border-top-left-radius: 30rpx;
  border-top-right-radius: 30rpx;
  padding: 30rpx;
  max-height: 70vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.modal-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

.modal-product-info {
  display: flex;
  margin-bottom: 30rpx;
}

.modal-product-img {
  width: 180rpx;
  height: 180rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
  object-fit: cover;
}

.modal-product-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.modal-product-title {
  font-size: 30rpx;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.modal-product-price {
  font-size: 18px;
  color: #ff0000;
  font-weight: bold;
}

.modal-product-stock {
  font-size: 14px;
  color: #999;
  margin: 5px 0;
}

.modal-product-shipping {
  font-size: 24rpx;
  color: #999;
}

.quantity-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.selector-label {
  font-size: 30rpx;
  color: #333;
}

.quantity-controls {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  background-color: #f5f5f5;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 36rpx;
  color: #333;
}

.quantity-value {
  width: 80rpx;
  text-align: center;
  font-size: 30rpx;
  margin: 0 20rpx;
}

.modal-coupon {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.modal-spec {
  width: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 30px;
}

.spec-label {
  font-size: 30rpx;
  width: 100%;
  margin-bottom: 20rpx;
}

.spec-values {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

/* 规格选择样式 */
.spec-text {
  background-color: #F5F5F5;
  color: #000000;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 24rpx;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
}

.spec-text.spec-default {
  background-color: #ff0000;
  color: #ffffff;
  width: 10%;
}

.spec-text.spec-selected {
  background-color: #ff0000;
  color: #ffffff;
}

.spec-values {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.spec-label {
  font-size: 30rpx;
  width: 100%;
  margin-bottom: 10rpx;
}

.modal-spec {
  width: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 20rpx;
}

.confirm-button {
  width: 100%;
  height: 100rpx;
  background-color: #ff0000;
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20rpx;
}
</style>
